from fastapi import APIRouter, Query,UploadFile
from tortoise.expressions import Q

from app.settings import settings
from app.controllers.content.content import content_controller
from app.schemas.base import Success, SuccessExtra,Fail
from app.schemas.content import *
from app.utils.upload import upload_image,upload_file
from typing import List

contents_router = APIRouter()


@contents_router.get("/list", summary="素材列表")
async def list_content(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        title: str = Query(None, description="素材名称"),
        tags: str = Query(None, description="标签名称"),
        type: str = Query(None, description="类型"),
        parent_id: int = Query(0, description="分类ID"),
):
    q = Q()
    if title:
        q &= Q(title__contains=title)
    if tags:
        q &= Q(tags__contains=tags)
    if type:
        q &= Q(type=type)
    if parent_id:
        q &= Q(parent_id=parent_id)
    total, data = await content_controller.content_list(page=page, page_size=page_size, search=q)
    for item in data:
        item["parent"] = item["parent_id"]
        item["type_name"] = settings.CONTENT_TYPE[item["type"]]
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

@contents_router.get("/get", summary="查看素材")
async def get_content(
        data_id: int = Query(..., description="素材ID"),
):
    data = await content_controller.content_get(data_id=data_id)
    return Success(data=data)

@contents_router.post("/create", summary="创建素材")
async def create_content(
        data_in: ContentCreate,
):
    await content_controller.content_create(obj_in=data_in)
    return Success(msg="创建成功")

@contents_router.post("/update", summary="更新素材")
async def update_content(
        data_in: ContentUpdate,
):
    await content_controller.content_update(obj_in=data_in)
    return Success(msg="更新成功")

@contents_router.delete("/delete", summary="删除素材")
async def delete_content(
        data_id: int = Query(..., description="素材ID"),
):
    await content_controller.content_delete(data_id=data_id)
    return Success(msg="删除成功")

@contents_router.post("/file", summary="上传缩略图")
async def file_content(file: UploadFile):
    url = await upload_image(file,"content/file")
    if not url:
        return Fail(code=400, msg="图片格式错误")
    data = {"url": url}
    return Success(data=data)

@contents_router.post("/files", summary="上传多文件")
async def files_content(file: UploadFile):
    url = await upload_file(file, "content/file")
    if not url:
        return Fail(code=400, msg="格式错误")
    data = {"url": url}
    return Success(data=data)
